/**
 *
 */
package com.androidnetframe.httputil;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.ConfigUtil;
import com.androidnetframe.cache.FileCacheFactory;
import com.androidnetframe.exception.CodeTypeHandler;
import com.androidnetframe.exception.CodeTypeObject;
import com.androidnetframe.exception.TypeCode;
import com.androidnetframe.requestbean.BaseRequestBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.AppUtils;
import com.androidnetframe.utils.CustomToast;
import com.androidnetframe.utils.LogUtils;
import com.androidnetframe.utils.UIUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.PublicKey;

/**
 * @author 何强
 *         2015-8-27
 */
public abstract class BaseRequestFilterLayer {
/*字符集编码----------------------------------------------------------------------*/
    /**
     * 7位ASCII字符，也叫作ISO646-US、Unicode字符集的基本拉丁块
     */
    public static final String US_ASCII = "US-ASCII";
    /**
     * ISO拉丁字母表 No.1，也叫做ISO-LATIN-1
     */
    public static final String ISO_8859_1 = "ISO-8859-1";
    /**
     * 8 位 UCS 转换格式
     */
    public static final String UTF_8 = "UTF-8";
    /**
     * 16 位 UCS 转换格式，Big Endian(最低地址存放高位字节）字节顺序
     */
    public static final String UTF_16BE = "UTF-16BE";
    /**
     * 16 位 UCS 转换格式，Litter Endian（最高地址存放地位字节）字节顺序
     */
    public static final String UTF_16LE = "UTF-16LE";
    /**
     * 16 位 UCS 转换格式，字节顺序由可选的字节顺序标记来标识
     */
    public static final String UTF_16 = "UTF-16";
    /**
     * 中文超大字符集
     **/
    public static final String GBK = "GBK";
    public static final String GB2312 = "GB2312";
/*字符集编码----------------------------------------------------------------------*/
    
    
/*BaseActivity------------------------------------------------------------------*/

    /*BaseActivity------------------------------------------------------------------*/
/*Loadding---------------------------------------------------------------------*/
    public boolean isNeedNoNetLayout = true;
    public boolean isNeedRequestFailedLayout = true;
    public boolean isNeedLoaddingLayout = true;
    public boolean isNeedNoDataLayout = true;

    public static final int no_net_failed = 1;
    public static final int request_connect_failed = 2;
    public static final int serverOther_response_failed = 3;
    public static final int server2002_response_failed = 4;
    public int failedType;
/*Loadding---------------------------------------------------------------------*/

    /*请求参数------------------------------------------------------------------*/
    public MakeRequestParams makeRequestParams;
    public boolean isRepeat = false;

	/*public static boolean needLoaginPage = true;*/
/*请求参数------------------------------------------------------------------*/

    /*UI缓存---------------------------------------------------------------------*/
    public boolean haveNetFromCache = false;
    public boolean haveNet_HaveOutOfDate = true;
    public boolean noNetFromCache = true;
    public boolean noNet_NoOutOfDate = true;

	/*内存缓存---------------------------------------------------------------------*/
    /**
     * 文件缓存的过期时间，默认值1分钟
     */
    public int memoryCacheOutOfDate = 60;
    /*内存缓存---------------------------------------------------------------------*/
    /*数据库缓存---------------------------------------------------------------------*/
    /**
     * 是否要开启数据库缓存
     */
    public boolean openDataBaseCache = false;//不开启
    /**
     * 数据库缓存的过期时间SharedPreference key
     */
    public final String DATABASECACHEKEY = "dataBaseCacheKey";
    /**
     * 数据库缓存的过期时间
     */
    public int dataBaseCacheTime = 10 * 60;
    /*数据库缓存---------------------------------------------------------------------*/

	/*sdcard缓存---------------------------------------------------------------------*/
    /**
     * sdcard缓存的过期时间
     */
    public int sdcardCacheTime = 10 * 60;
    /*sdcard缓存---------------------------------------------------------------------*/

	
	
	
/*UI缓存---------------------------------------------------------------------*/
    /**
     * 真正进行网络处理的对象
     */
    private NetProcessFactory netProcessFactory;
    /**
     * 对外提供字符集编码的设置
     */
    public String charsetString = UTF_8;
    /**
     * 外面设置的泛型的类名
     */
    private String genericsString;
    /**
     * 外面设置的泛型的全类名
     */
    private String completeClassName;
    /**
     * 记录返回的类型
     */
    private int returnType;

    /**
     * 是否需要开启对请求回来的数据进行缓存，默认开启
     */
    public boolean openRequestDataCache = false;//不开启
    public FileCacheFactory fileCacheFactory;
    /**
     * 是否要从缓存中取数据
     */
    public boolean getFromCache = false;

    /**数据库缓存时间*/
    /**
     * 数据库缓存的过期时间 key
     */
    public final String DB_CACHETIME = "cacheTime";
    public Context context;

    public boolean haveOutOfdate = true;
    public String noOutOfDateCacheData;
    public boolean needMerge = false;
    /**
     * 是否需要开启磁盘缓存
     */
    public boolean needSdcardCache = true;//开启
    /**
     * 是否是实时页面
     */
    public boolean realTimePage = false;
    /**
     * 数据库表中最新的id
     */
    public int dbLatestID = -1;
    public boolean requestOk = false;

    /*展示界面相关的参数---------------------------------*/
    public ViewGroup errorRootView;
    public int codeType = TypeCode.ConnectFailed;
    public boolean overideLayoutMatchParent = false;
    public boolean requestDone;

    public Dialog dialog;
    /**
     * 设置loadding框的背景是否为透明
     */
    public boolean isTransparence = false;//false：不透明 true：透明
/*展示界面相关的参数---------------------------------*/

/*返回数据---------------------------------*/
    /**
     * 代表请求是否成功，true成功，false失败
     */
    public boolean isResponseError;
    public RequestError requestError;
    public static String tokenId;
/*返回数据---------------------------------*/

    /*加密和解密---------------------------------*/
    public static final int AES = 0;
    public static final int RSA = 1;
    /**
     * 默认需要加密
     */
    public boolean isNeedEncrypt = false;
    public int requestEncryptMethod = AES;
    public int responseDecryptMethod = AES;
    /*加密和解密---------------------------------*/
    SharedPreferences settings;
    Editor localEditor;
    int version=0;

    public CustomToast customToast;
    public int toastShowTime = 3000;

    public RequestParams requestParams;
    public BaseRequestFilterLayer(BaseParentActivity context) {
        /*初始化参数对象*/
        makeRequestParams = new MakeRequestParams();
        makeRequestParams.setContext(context);

        //上传的数据参数
        requestParams = new RequestParams();

        settings = makeRequestParams.activity.getSharedPreferences("TokenId_Folder", 0);
        localEditor = settings.edit();

        version =AppUtils.getVersionCode(context);
        /*创建自定义的Toast*/
        customToast = new CustomToast(makeRequestParams.activity);
        /*创建真正请求的网络处理类*/
        netProcessFactory = new NetProcessFactory();
    }
    public <T> void sendRequest(AccessResultFromFilter<T> accessResult) {
        /*将传进来的函数参数保存起来*/
        this.accessResultFromFilter = accessResult;
        //将请求的参数bean类，转化为json
        if (makeRequestParams.haveRequestParams) {
            upLoaddingJson(makeRequestParams.obj);
        }
        /*获取AccessResult所包含泛型的全类名和类名*/
        String[] tempString = getGenericsName(accessResult);
        completeClassName = tempString[0];//如：完整的类名：com.example.httputil.NetRequestFilterLayer
        genericsString = tempString[1];//如：类名：NetRequestFilterLayer

        willRequest();
    }

    public String noNet() {
        return null;
    }

    /**
     * true:获取数据成功
     * false:获取数据失败
     */
    private boolean getDataFromCache(boolean haveOutOfDate) {
        fileCacheFactory = ConfigUtil.fileCacheFactory;
        //看内存中是否有缓存文件
        fileCacheFactory.memoryCacheOutOfDate = memoryCacheOutOfDate;
        boolean[] jsonMemoryState = fileCacheFactory.getJsonStringStateFromMemory(makeRequestParams.entryPageName);
        if (jsonMemoryState[0]) {//先看内存中该文件是否存在
            if (haveOutOfDate) {//需要判断过期时间
                if (jsonMemoryState[1]) {//文件内容没有过期
                    String tempData = fileCacheFactory.getJsonStringFromMemory();
                    callUIOnsuccessMethod(bytesToJavaBeanObject(tempData.getBytes(), completeClassName));
                    return true;
                }
            } else {//不需要判断过期时间
                String tempData = fileCacheFactory.getJsonStringFromMemory();
                callUIOnsuccessMethod(bytesToJavaBeanObject(tempData.getBytes(), completeClassName));
                return true;
            }

        }
        //从数据库中取缓存
        if (getCacheDataFromDataBase(haveOutOfDate)) {
            return true;
        }
        //从sdcard中获取缓存
        fileCacheFactory.sdcardCacheOutOfDate = sdcardCacheTime;
        boolean[] jsonSdcardState = fileCacheFactory.getJsonStringStateFromSdcard(makeRequestParams.entryPageName);
        if (jsonSdcardState[0]) {//再看Sdcard中是否存在该文件
            if (haveOutOfDate) {//需要判断过期时间
                if (jsonSdcardState[1]) {//没有过期
                    String tempData = fileCacheFactory.getJsonStringFromSdcard(makeRequestParams.entryPageName);
                    callUIOnsuccessMethod(bytesToJavaBeanObject(tempData.getBytes(), completeClassName));
                    return true;
                } else {
                    return false;
                }
            } else {//不需要判断过期时间
                String tempData = fileCacheFactory.getJsonStringFromSdcard(makeRequestParams.entryPageName);
                callUIOnsuccessMethod(bytesToJavaBeanObject(tempData.getBytes(), completeClassName));
                return true;
            }
        } else {
            return false;//两个地方都没有，直接从网络上获取
        }
    }

    /**
     * 应该从网络上取数据还是从缓存中取数据
     * return true:从网络上取数据，false：不从网络上取数据
     */
    private boolean getCacheNoExpireTime() {
        //看内存中是否有缓存文件
        if (queryDataFromMemoryCache(makeRequestParams.entryPageName)) {
            return true;
        }

        //看数据库中是否有缓存的文件
        if (getCacheDataFromDataBase(false)) {
            return true;
        }
        //看sdcard中是否有缓存文件
        boolean[] jsonSdcardState = fileCacheFactory.getJsonStringStateFromSdcard(makeRequestParams.entryPageName);
        if (jsonSdcardState[0]) {//再看Sdcard中是否存在该文件
            String tempData = fileCacheFactory.getJsonStringFromSdcard(makeRequestParams.entryPageName);
            noOutOfDateCacheData = tempData;
            return true;
        } else {//三个地方都没有
            return false;
        }
    }

    private boolean haveNetRun() {

		/*}else{//不需要从缓存中获取
            return true;
		}*/
        return true;
    }

    /**
     * 返回值: true：获取到了缓存数据
     * false：没有获取到缓存数据
     * noCacheTime:true:需要判断缓存时间
     * false:不需要判断缓存时间
     */
    private boolean getCacheDataFromDataBase(boolean noCacheTime) {
        if (openDataBaseCache) {//是否要开启数据库缓存
            /*从SharedPreferences获取数据库之前的存放时间*/
            SharedPreferences preferences = makeRequestParams.activity.getSharedPreferences(DATABASECACHEKEY, Context.MODE_PRIVATE);
            long cache = preferences.getLong(makeRequestParams.entryPageName, 0);
            if (noCacheTime) {
                //判断数据库缓存是否过期
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - cache > dataBaseCacheTime) {//过期 注意：如果数据表文件不存在，也会是过期状态
                    return false;
                } else {//没有过期
                        /*从数据库获取相应的数据，然后回调到前台*/
                    callExternalFunction(readFromDataBase(), completeClassName, accessResultFromFilter);
                    return true;
                }
            } else {
                //如果数据库缓存文件存在，不需要判断是否过期，直接取出来
                if (cache > 0) {//数据表存在
                    callExternalFunction(readFromDataBase(), completeClassName, accessResultFromFilter);
                    return true;
                }
            }
        }
        return false;
    }

		/*本类所使用的方法----------------------------------------------------------------------------------------------------------------*/

    /**
     * 将请求的结果转化为javaBean返回
     */
    public void callUIOnsuccessMethod(Object object) {
        if (object == null) {
            callExternalFunction(null, completeClassName, accessResultFromFilter);
        } else {
            try {
                //暂时没什么用，仅保留
                if (object instanceof RequestError) {//如果是请求错误的话，向UI返回null
                    callExternalFunction(null, completeClassName, accessResultFromFilter);
                    return;
                }
                isRepeat = false;
                callExternalFunction(object, completeClassName, accessResultFromFilter);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /*返回请求结果类中泛型的全类名和类名
     * name[0]:是泛型的全类名
     * name[1]:是泛型的类名
     * */
    public String[] getGenericsName(Object accessResult) {
        String[] name = new String[2];
        Type type = accessResult.getClass().getGenericInterfaces()[0];
        String string = type.toString();//com.example.httputil.BaseRequestFilterLayer$AccessResultFromFilter<com.example.testnetframe.network.javabean.AddAddress>
        name[0] = string.substring(string.indexOf('<') + 1, string.length() - 1);
        name[1] = string.substring(string.lastIndexOf('.') + 1, string.length() - 1);
        return name;
    }

    /*该方法负责调用外部的接口并传递参数*/
    public void callExternalFunction(Object obj, String completeClassName, AccessResultFromFilter<?> accessResultListener) {
        try {
            Class<?> generics = Class.forName(completeClassName);
            Class<? extends AccessResultFromFilter> class1 = accessResultListener.getClass();
            Method method = class1.getDeclaredMethod("onSuccess", generics);
            method.invoke(accessResultListener, obj);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 这个方法，主要是给子类使用的，看得到数据之前，看是否还要做一些什么其他的工作
     */
    public void getResultSuccess(String responseString, Object obj) {

    }

    /**
     * 这个方法，主要是给子类使用的，如果获取数据失败了，看是否还要做一些什么其他的工作
     * return :返回具体的错误类型给父类，父类可以根据这一错误类型做相应的处理
     */
    public int getResultFailed(HttpException exception, String descException) {
        return TypeCode.ConnectFailed;
    }

    public void setRequestError(String isError, String errCode, String mess) {
        if (requestError == null)
            requestError = new RequestError();
        requestError.isError = isError;
        requestError.errCode = errCode;
        requestError.mess = mess;
    }

	/*本类所使用的方法----------------------------------------------------------------------------------------------------------------*/

	/*本类所使用的类-------------------------------------------------------------------------------------------------------------------*/

    /*返回值类型的类*/
    public class ReturnType {
        public static final int Json = 10000;
        public static final int JavaBean = 10001;
        public static final int ByteArray = 10002;
        public static final int CommonString = 10003;
    }

    /*继承网络请求处理器的回调结果的类*/
    public class MyNetFactoryAccessResult implements NetProcessFactory.NetFactoryAccessResult {
        ViewGroup rootView;
        int errorType;
        BaseRequestFilterLayer filter;

        public MyNetFactoryAccessResult(ViewGroup rootView, int errorType, BaseRequestFilterLayer filter) {
            this.rootView = rootView;
            this.errorType = errorType;
            this.filter = filter;
        }

        @Override//请求成功产生的回调
        public void accessResultSuccess(byte[] data) {
             Log.e("Test", "基本请求过滤层：请求网络连接成功");
            //网关返回错误状态
            isResponseError = false;
            /**告诉BaseParentActivity，如果还没有加载完View的话，不要再加载View了*/
            requestDone = true;
            //假设有错误布局的情况下：移除错误布局
            makeRequestParams.activity.removeErrorLayout(filter);

            //移除loadding框
            makeRequestParams.activity.removeLoadingLayout(filter);
            isResponseError = false;//没有返回错误

            //是否需要跳转到登陆页面
            JSONObject jsonObject = null;
            try {
                String s = new String(data);
                Log.e("TestBaseRequestFilter",BaseRequestFilterLayer.this.toString()+"--data-----"+s);
                jsonObject = new JSONObject(s);
                if(null == jsonObject){
                    return;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (processCode(jsonObject)) {//是否需要跳转到登陆界面
                return;
            }

				/*对请求回来的数据进行解密*/
          /*  data = decryptData(data);*/
                /*是否开启请求数据缓存*/
            if (openRequestDataCache) {
                //对请求回来的数据进行缓存
                cacheResponseData(data);
            }
            //将返回来的数据进行统一处理

            int code = (int) jsonObject.optInt("code");
            if (code == 0) {//数据请求成功，调用成功的接口
                callUIOnsuccessMethod(bytesToJavaBeanObject(data, completeClassName));
            } else if(code == 10000) {//专门针对10000提示信息，商品下架
                callUIOnsuccessMethod(bytesToJavaBeanObject(data, completeClassName));
            }else{//非0，统一定为失败
                setRequestError(null, String.valueOf(jsonObject.optInt("code")), jsonObject.optString("message"));
                requestDone = false;//重置标志，为的是到时能重新加上错误页面
                /*添加错误页面*/
                if (isNeedRequestFailedLayout) {
                    int resultFailed = getRequestFailedCodeType();
                    addOverideLayoutToBaseActivity(resultFailed);
                }
                if(code==300){
//                    context.startActivity(new Intent(context,LoginActivity.class));
                }
                accessResultFromFilter.onFailed(null, requestError, code);
            }

        }

        /*private byte[] decryptData(byte[] data) {
            if (isNeedEncrypt) {//是否需要加密
                switch (responseDecryptMethod) {
                    case AES:
                        return aesdecrypt(ConfigUtil.getAESInstance(makeRequestParams.activity), new String(data, Charset.forName(UTF_8))).getBytes();
                }
            }
            return data;
        }*/

        @Override//请求失败产生的回调
        public void accessResultFailed(HttpException exception, String descException) {
                /*基本的抽象过滤层：默认先打印一行日志，请求网络连接失败*/
            Log.e("TestBaseRequestFilter",BaseRequestFilterLayer.this.toString()+"基本请求过滤层：请求网络连接失败");
            failedType = request_connect_failed;
            requestDone = false;//重置标志，为的是到时能重新加上错误页面
                /*添加错误页面*/
            if (isNeedRequestFailedLayout) {
                int resultFailed = getRequestFailedCodeType();
                addOverideLayoutToBaseActivity(resultFailed);
            }
            getResultFailed(exception, descException);
            setRequestError(null, String.valueOf(exception.getExceptionCode()), descException);
            accessResultFromFilter.onFailed(null, requestError, failedType);
            //移除loadding框
            makeRequestParams.activity.removeLoadingLayout(filter);
        }

        private void cacheResponseData(byte[] data) {
            if (needSdcardCache) {
                //保存到内存和Sdcard中
                ConfigUtil.fileCacheFactory.saveJson(makeRequestParams.entryPageName, new String(data));
            }
            //保存到数据库中
            if (openDataBaseCache) {
                saveToDB(data);
            }
        }

        private void saveToDB(byte[] data) {
            SharedPreferences preferences = makeRequestParams.activity.getSharedPreferences(DATABASECACHEKEY, Context.MODE_PRIVATE);
            Editor editor = preferences.edit();
            long time = System.currentTimeMillis();
            editor.putLong(makeRequestParams.entryPageName, time);
            editor.commit();
            try {
                String jsonString = new String(data, charsetString);
                saveToDataBase(jsonString);
            } catch (UnsupportedEncodingException e) {

            }
        }

    }

    protected boolean processCode(JSONObject jsonObject) {

        if(jsonObject==null){
            return false;
        }
        int code = (int) jsonObject.opt("code");
        LogUtils.e("codeabc",code);
        switch (code) {
            case 300://登陆失效
                setRequestError(null, String.valueOf(jsonObject.optInt("code")), jsonObject.optString("message"));
                accessResultFromFilter.onFailed(null, requestError, -1);
                Intent backToLogin;
                try {
								/*	if(needLoaginPage){
										needLoaginPage = false;*/
                    backToLogin = new Intent(
                            makeRequestParams.activity, Class.forName("com.mmlc.meimei.meiqi.mine.LoginActivity"));
                    backToLogin.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    Toast.makeText(makeRequestParams.activity,"登录过期，请重新登录",Toast.LENGTH_LONG).show();
//                    makeRequestParams.activity.startActivity(backToLogin);
//                    makeRequestParams.activity.finish();
								/*	}*/

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
			/*default://请求参数错误，展示错误页面
				requestDone = false;//重置标志，为的是到时能重新加上错误页面
				failedType = serverOther_response_failed;
				//移除Loading框
				makeRequestParams.activity.removeLoadingLayout(filter);
				//添加错误页面
				if(isNeedRequestFailedLayout){
					int resultFailed = TypeCode.loginNoNet;
					addOverideLayoutToBaseActivity(resultFailed,requestError.mess,"textView");
				}
				accessResultFromFilter.onFailed(null,requestError,failedType);
				return;*/

        }
        return false;
    }
/*本类所使用的-------------------------------------------------------------------------------------------------------------------*/
		/*本类所使用的方法*/

    /**
     * 从数据库中读取数据
     */
    public Object readFromDataBase() {
        return null;
    }

    /**
     * 将数据保存到数据库中
     */
    public void saveToDataBase(String jsonString) {
    }

    /**
     * 实时页面无网络时调用
     */
    public void realTimePageNoNet(String url, String completeClassName, AccessResultFromFilter<?> accessResult) {

    }

    /**
     * 从内存中查询缓存的数据-不考率过期时间
     */
    public boolean queryDataFromMemoryCache(String entryPageName) {
        boolean[] jsonMemoryState = fileCacheFactory.getJsonStringStateFromMemory(makeRequestParams.entryPageName);
        if (jsonMemoryState[0]) {//先看内存中该文件是否存在
            String tempData = fileCacheFactory.getJsonStringFromMemory();
            noOutOfDateCacheData = tempData;
            //Toast.makeText(ConfigUtil.context, "MemoryData="+jsonMemoryState[0]+"-"+jsonMemoryState[1], 4000).show();
            return true;
        }
        return false;
    }

   /* public Dialog centerLayoutOnScreen(View view) {
        //对话框
        final Dialog dialog = new AlertDialog.Builder(makeRequestParams.activity, R.style.DialogStyle).create();
        dialog.show();
        //点击Dialog显示视图之外的地方和back键不让当前Dialog消失
        dialog.setCanceledOnTouchOutside(false);//
        dialog.getWindow().setContentView(view);
        return dialog;
    }*/

    public void closeShowCenterInParentLayout(final Dialog dialog) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(2000);
                    dialog.dismiss();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
                .start();
    }

    public Object bytesToJavaBeanObject(byte[] data, String completeClassName) {
        try {
            String jsonString = new String(data, charsetString);
            jsonString = unescapeUnicode(jsonString);

            if (genericsString.equals("String")) {
                getResultSuccess(jsonString, null);
                return jsonString;
            }
            Class<?> generics = Class.forName(completeClassName);
//            Gson gson = new Gson();
//            Object obj = gson.fromJson(jsonString, generics);
            Object obj = JSON.parseObject(jsonString, generics);
            getResultSuccess(jsonString, obj);
            return obj;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String unescapeUnicode(String pStr) {
		/*HashMap<String,String> map = new HashMap<String,String>();
		String[] key_value = str.split(",");
		for(int i=0;i<key_value.length;i++){
			String[] result = key_value[i].split(":");//result[0]==key result[1] = value
			String tmpKey = result[0].replace("\"","").replace("{","");
			String tmpValue = result[1].replace("\"","").replace("}","");
			Matcher m = Pattern.compile("\\\\u([0-9a-fA-F]{4})").matcher(tmpValue);
			while(m.find()){
				char c = (char)Integer.parseInt(m.group(1),16);
				tmpValue = tmpValue.replace("\\u" + m.group(1), c + "");
				m = Pattern.compile("\\\\u([0-9a-fA-F]{4})").matcher(tmpValue);
			}
			map.put(tmpKey,tmpValue);
		}
		return new Gson().toJson(map);*/
        char aChar;
        int len = pStr.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = pStr.charAt(x++);
            if (aChar == '\\') {
                aChar = pStr.charAt(x++);
                if (aChar == 'u') {
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = pStr.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed      encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't') {
                        aChar = '\t';
                    } else if (aChar == 'r') {
                        aChar = '\r';
                    } else if (aChar == 'n') {
                        aChar = '\n';
                    } else if (aChar == 'f') {
                        aChar = '\f';
                    } else if (aChar == '"') {
                        outBuffer.append('\\');
                        aChar = '\"';
                    } else if (aChar == '\\') {
                        outBuffer.append('\\');
                        aChar = '\\';
                    }
                    outBuffer.append(aChar);
                }
            } else {
                outBuffer.append(aChar);
            }
        }
        return outBuffer.toString();
    }

    /**
     * AES加密
     */
   /* public String aesEncrypt(AES mAes, byte[] mBytes) {
       *//* return mAes.encrypt(mBytes);*//*
    }*/

    /**
     * AES解密
     */
    /*public String aesdecrypt(AES mAes, String encryptString) {

        return mAes.decrypt(encryptString);
    }*/

    /**
     * RSA加密
     */
    public String rsaEncrypt(String public_key, byte[] dataSource) {
        // 从字符串中得到公钥
        PublicKey publicKey;
        try {
           /* publicKey = RSAUtils.loadPublicKey(public_key);*/
				/*// 从文件中得到公钥
				InputStream inPublic = getResources().getAssets().open("rsa_public_key.pem");
				PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);*/
            // 加密
            //String str = "hello";
            //String str1 = "{\"paras\":{\"sortRule\":\"desc\",\"sortField\":\"placeOrderTime\",\"pageSize\":10,";//+"\"pageNum\":1},\"tokenId\":\"4bb0c32ddbd843eca413b974c72cddfe\"}";
            //String str2 = "\"pageNum\":1},\"tokenId\":\"4bb0c32ddbd843eca413b974c72cddfe\"}";
            //String str3 = str1+str2;
           /* byte[] encryptByte = RSAUtils.encryptData(dataSource, publicKey);
            // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
            return Base64Utils.encode(encryptByte);*/
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA解密
     */
    public String rsaDecrypt(String private_key, String dataSource) {
        // 从字符串中得到私钥
        try {
           /* PrivateKey privateKey = RSAUtils.loadPrivateKey(private_key);*/
					/*// 从文件中得到私钥
					InputStream inPrivate = getResources().getAssets().open(private_key"pkcs8_rsa_private_key.pem");
					PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);*/
            // 因为RSA加密后的内容经Base64再加密转换了一下，所以先Base64解密回来再给RSA解密
          /*  byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(dataSource), privateKey);
            return new String(decryptByte, Charset.forName(UTF_8));*/
        } catch (Exception e) {

        }
        return dataSource;
    }

    public void directShowView(View view, int toastShowTime) {
        CustomToast customToast = new CustomToast(makeRequestParams.activity);
        customToast.setView(view);
        customToast.setDuration(toastShowTime);
        //设置WindowManger能够显示的区域
        customToast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
        customToast.show();
    }
/*本类所使用的-------------------------------------------------------------------------------------------------------------------*/
	
		
/*定义接口---------------------------------------------------------------------*/

    /**
     * 泛型只能JavaBean
     */
    public AccessResultFromFilter<?> accessResultFromFilter;

    public interface AccessResultFromFilter<T> {
        public void onSuccess(T result);

        public void onFailed(View errorLayout, RequestError serverError, int failedType);
    }
/*定义接口--------------------------------------------------------------------*/
		
		
/*外部调用--------------------------------------------------------------------*/

    /**
     * 用于设置网络请求参数
     */
    public void setRequestParams(RequestParams params) {
        netProcessFactory.setRequestParams(params);
    }

    public void addOverideLayoutToBaseActivity(int codeType) {
        CodeTypeHandler codeTypeHandler = ConfigUtil.codeTypeHandler;
        CodeTypeObject codeTypeObject = codeTypeHandler.processCodeType(codeType);
        if (codeTypeObject.isDerectShow) {//如果是直接显示
            directShowView(codeTypeObject.view, toastShowTime);
        } else {//如果不是直接显示
            makeRequestParams.activity.addOverideLayout(errorRootView, isTransparence, codeTypeObject, BaseRequestFilterLayer.this);
        }
    }

    public void addOverideLayoutToBaseActivity(int codeType, String message, String viewId) {
        CodeTypeHandler codeTypeHandler = ConfigUtil.codeTypeHandler;
        CodeTypeObject codeTypeObject = codeTypeHandler.processCodeType(codeType);
        if (message != null) {
            int textViewId = makeRequestParams.activity.getResources().getIdentifier(viewId, "id", makeRequestParams.activity.getPackageName());
            TextView text = (TextView) codeTypeObject.view.findViewById(textViewId);
            text.setText(message);
        }
        if (codeTypeObject.isDerectShow) {//如果是直接显示
            directShowView(codeTypeObject.view, toastShowTime);
        } else {//如果不是直接显示
            makeRequestParams.activity.addOverideLayout(errorRootView, isTransparence, codeTypeObject, BaseRequestFilterLayer.this);
        }
    }

    /**
     * 上传json
     * Object objJson:能转化为json结构的类
     */

    public void upLoaddingJson(Object objJson) {
        if (objJson instanceof BaseRequestBean) {
            //获取Token的值
            String token = getTokenId();
            ((BaseRequestBean) objJson).token = token;
            ((BaseRequestBean) objJson).version = version+"";

            LogUtils.w("objJson", objJson.toString());

        }
        try {
            UIUtils.objToHash(objJson, requestParams);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
		/*	params.setContentType("application/x-www-form-urlencoded");
			params.setBodyEntity(new StringEntity(json));*/

        makeRequestParams.setRequestParams(requestParams);
    }

    public void setDebug(boolean debug) {
        netProcessFactory.debug = debug;
    }

    public String tempTestDescrypt(String json) {
        /*if (isNeedEncrypt) {//是否需要加密
            switch (responseDecryptMethod) {
                case AES:
                    return aesdecrypt(ConfigUtil.getAESInstance(makeRequestParams.activity), json);
                case RSA:
                    return rsaDecrypt(MainActivity.PRIVATE_KEY, json);
            }
        }*/
        return json;
    }

    public void saveTokenId(String tokenId) {

        //A_MAP03类必需要继承了Activity的子类 才会有getSharedPreferences方法.
        //以键值<String Key,String Value> 方式加入数据
        localEditor.putString("TokenId", tokenId);
        localEditor.commit();
    }

    public String getTokenId() {
        return settings.getString("TokenId", null);
    }

    public static boolean deleteTokenId(Context context) {
        SharedPreferences settings = null;
        Editor localEditor = null;
        settings = context.getSharedPreferences("TokenId_Folder", 0);
        localEditor = settings.edit();
        return localEditor.clear().commit();
    }

    public String getRequestURL() {
        return netProcessFactory.requestURL;
    }
		/*方法=========================================================================================*/
		
		/*方法=========================================================================================*/
/*外部调用--------------------------------------------------------------------*/
		

		

/*子类必须实现----------------------------------------------------------------------------------*/

    public void offerErrorParams(ViewGroup rootView) {
        this.errorRootView = rootView;
    }
/*子类必须实现----------------------------------------------------------------------------------*/

    /*子类视情况覆盖----------------------------------------------------------------------------------*/
    public boolean isChildProcess(byte[] data) {
        return false;
    }

    public int getLoaddingCodeType() {
        return TypeCode.requestNetLoadding;
    }

    public int getNoNetCodeType() {
        return TypeCode.NoNet;
    }

    public int getRequestFailedCodeType() {
        return TypeCode.ConnectFailed;
    }
/*子类视情况覆盖----------------------------------------------------------------------------------*/

    /*回调区----------------------------------------------------------------------------------*/
		/*重新发起网络请求*/
    public void errorRefresh() {
        BaseParentActivity.OverideParams errorParams = makeRequestParams.activity.filterRootView_errorView.get(this.hashCode()+this.getClass().getName());
        if (errorParams != null) {
            isRepeat = true;//当执行这行代码，就代表重复请求
            errorParams.filter.sendRequest(accessResultFromFilter);
        }
    }

    /*回调区----------------------------------------------------------------------------------*/
/*
	首次需要请求网络
*/
    public static boolean fetchOk = false;

    public FirstRequest firstRequest;

    public interface FirstRequest {
        void run(boolean isSuccess);
    }

    public void setFirstRequestListener(FirstRequest firstRequest) {
        this.firstRequest = firstRequest;
    }

    RequestExcuter excuter;

    public void willRequest() {
        excuter = new RequestExcuter();
        //先判断有网无网
        if (ConfigUtil.netScanner.canConnectedNet) {//有网
            if (ConfigUtil.fetchState == -1) {//还在获取网络
                ConfigUtil.configUtil.setFirstRequestListener(excuter);
            } else if (ConfigUtil.fetchState == 1) {//获取成功
                excuter.run(true);
            } else if (ConfigUtil.fetchState == 2) {//获取失败
                ConfigUtil.configUtil.setFirstRequestListener(excuter);
                ConfigUtil.configUtil.fetchBaseUrlFromServer();
            }
        } else {//无网
            excuter.run(false);
        }

    }

    class RequestExcuter implements ConfigUtil.FirstRequest {

        @Override
        public void run(boolean isSuccess) {
            if (ConfigUtil.netScanner.canConnectedNet) {//有网
                if (haveNetFromCache) {//是否需要从缓存中获取数据
                    if (getDataFromCache(haveNet_HaveOutOfDate)) {//获取到了，直接就返回
                        return;
                    }
                }

			/*没有获取到数据，那么就从网络中，去获取，并展示Loadding框*/
                if (isNeedLoaddingLayout) {
                    //展示Loadding提示界面
                    int codeType = getLoaddingCodeType();
                    addOverideLayoutToBaseActivity(codeType);
                }
            } else {//无网
                if (noNetFromCache) {
				/*if(getDataFromCache(noNet_NoOutOfDate)){//获取到了，直接就返回
					return;
				}*/
                    String data = noNet();
                    if (data != null) {//已经从缓存中获取到数据了
                        callUIOnsuccessMethod(bytesToJavaBeanObject(data.getBytes(), completeClassName));
                        return;
                    }
                }
			/*没有获取到数据，就直接展示错误页面*/
                if (isNeedNoNetLayout) {
                    //展示无网提示界面
                    int codeType = getNoNetCodeType();
                    addOverideLayoutToBaseActivity(codeType);
                }
                setRequestError(null,-1+"","当前没有网络信号");
                accessResultFromFilter.onFailed(null, requestError, failedType);
                return;
            }
            netProcessFactory.setRequestObject(makeRequestParams, new MyNetFactoryAccessResult(errorRootView, codeType, BaseRequestFilterLayer.this));
        }
    }

    public void AddNoDataUI(){
        requestDone = false;//重置标志，为的是到时能重新加上错误页面
                /*添加错误页面*/
        if (isNeedNoDataLayout) {
            addOverideLayoutToBaseActivity(TypeCode.NoData);
        }
    }
}

